package com.xmg.p2p.base.service.impl;

import com.xmg.p2p.base.domain.Mailverify;
import com.xmg.p2p.base.domain.Userinfo;
import com.xmg.p2p.base.mapper.MailverifyMapper;
import com.xmg.p2p.base.mapper.UserinfoMapper;
import com.xmg.p2p.base.service.IMailService;
import com.xmg.p2p.base.service.IUserinfoService;
import com.xmg.p2p.base.service.IVerifyCodeService;
import com.xmg.p2p.base.util.BidConst;
import com.xmg.p2p.base.util.BitStatesUtils;
import com.xmg.p2p.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class UserinfoServiceImpl implements IUserinfoService {
    @Value("${mail.hostUrl}")
    private String hostUrl;
    @Autowired
    private UserinfoMapper userinfoMapper;
    @Autowired
    private MailverifyMapper mailverifyMapper;
    @Autowired
    private IVerifyCodeService verifyCodeService;
    @Autowired
    private IMailService mailService;


    @Override
    public void update(Userinfo userinfo) {
        int ret = userinfoMapper.updateByPrimaryKey(userinfo);
        if (ret == 0) {
            throw new RuntimeException("乐观锁失败,Userinfo:" + userinfo.getId());
        }
    }

    @Override
    public void add(Userinfo ui) {
        userinfoMapper.insert(ui);
    }

    @Override
    public Userinfo get(Long id) {
        return userinfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public void bindPhone(String phoneNumber, String verifyCode) {
        Userinfo current = get(UserContext.getCurrent().getId());
        if (!current.getIsBindPhone()) {
            boolean ret = verifyCodeService.verify(phoneNumber, verifyCode);
            if (ret) {
                current.addState(BitStatesUtils.OP_BIND_PHONE);
                current.setPhoneNumber(phoneNumber);
                update(current);
            } else {
                throw new RuntimeException("绑定手机失败");
            }
        }
    }

    @Override
    public void sendEmail(String email) {
        //当前用户是否绑定邮箱
        Userinfo current = getCurrent();
        if(!current.getIsBindEmail()){
            String uuid = UUID.randomUUID().toString();
            StringBuilder content = new StringBuilder(100)
                    .append("点击<a href=").append(hostUrl)
                    .append("bindEmail.do?key=").append(uuid)
                    .append(">这里</a>完成邮箱验证，有效期为")
                    .append(BidConst.VERIFYEMAIL_VAILDATE_DAY).append("天");
            try {
                System.out.println("发送邮件:" + email + "邮件内容:" + content);
                mailService.sendMail(email,"test",content.toString());
                Mailverify mv = new Mailverify();
                mv.setEmail(email);
                mv.setSenddate(new Date());
                mv.setUserinfoId(current.getId());
                mv.setUuid(uuid);
                mailverifyMapper.insert(mv);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("邮件发送失败");
            }
        }
    }

    @Override
    public Userinfo getCurrent() {
        return get(UserContext.getCurrent().getId());
    }

    @Override
    public void bindEmail(String key) {
        Mailverify mv = mailverifyMapper.selectByUUID(key);
        if(mv!=null){
            Userinfo current = get(mv.getUserinfoId());
            if(!current.getIsBindEmail()){
                current.setEmail(mv.getEmail());
                current.addState(BitStatesUtils.OP_BIND_EMAIL);
                userinfoMapper.updateByPrimaryKey(current);
                return;
            }
        }
        throw new RuntimeException("绑定邮箱失败");
    }

    @Override
    public void updateBasicInfo(Userinfo info) {
        Userinfo old = getCurrent();
        old.setEducationBackground(info.getEducationBackground());
        old.setHouseCondition(info.getHouseCondition());
        old.setIncomeGrade(info.getIncomeGrade());
        old.setKidCount(info.getKidCount());
        old.setMarriage(info.getMarriage());
        if(!old.getIsBasicInfo()){
            old.addState(BitStatesUtils.OP_BASIC_INFO);
        }
        update(old);
    }
}
